package com.winit.core.server.base;

import org.springframework.util.Assert;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * 抽象提供shell命令输出回调的处理类.
 * <p>
 * Created by keel2008 on 16/8/10.
 */
public abstract class CmdOutputHandler {

    public void handleCmdOutput(String cmd, int index, InputStream is,InputStream error) throws Exception {

        try {

            Assert.notNull(is);
            Assert.notNull(error);

            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            BufferedReader errorReader = new BufferedReader(new InputStreamReader(error));

            String buf;
            String errorBuf;

            do {
                buf = reader.readLine();
                errorBuf = errorReader.readLine();

                if (errorBuf != null){
                    onMessage(cmd, index, errorBuf,true);
                }

                if (buf != null){
                    onMessage(cmd, index, buf,false);
                }

            }while (buf != null || errorBuf != null);

        } catch (Exception e) {
            throw e;
        } finally {
            if (is == null) {
                is.close();
            }
        }
    }

    public abstract void onMessage(String cmd, int index, String message,Boolean isErrorMessage);
}
